<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="80%"
      :before-close="cancel"
      @open="open"
    >
      <div class="dialog-content">
        <el-descriptions title="标案信息" class="margin-top" :column="3" border>
          <el-descriptions-item label="标案名称">
            <el-input v-model="form.params.tenderName" />
          </el-descriptions-item>
          <el-descriptions-item label="标案编码" :span="2">
            <el-input v-model="form.params.tenderCode" />
          </el-descriptions-item>
          <el-descriptions-item label="招标类型">
            <el-select v-model="form.params.tenderType" disabled>
              <el-option
                v-for="item in productTypes"
                :key="item.id"
                :label="item.productType"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-descriptions-item>

          <el-descriptions-item label="招标项目">
            <el-select
              v-model="form.params.tenderProject"
              clearable
              filterable
              @change="projectSelect"
              placeholder="请选择招标项目"
            >
              <el-option
                v-for="item in projects"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="立标日期">
            <el-date-picker
              v-model="form.params.tenderTime"
              type="datetime"
              placeholder="选择立标日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              disabled
            >
            </el-date-picker>
          </el-descriptions-item>
          <el-descriptions-item label="招标负责人">
            <el-input v-model="form.params.tenderCharge" />
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <el-input v-model="form.params.tenderPhone" />
          </el-descriptions-item>
          <el-descriptions-item label="固定电话">
            <el-input v-model="form.params.tenderTel" />
          </el-descriptions-item>
          <el-descriptions-item label="招标方式">
            <el-select
              v-model="form.params.tenderMode"
              clearable
              placeholder="请选择招标方式"
            >
              <el-option label="公开招标" value="0"> </el-option>
              <el-option label="非公开招标" value="1"> </el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="竞价方式">
            <el-select
              v-model="form.params.biddingMode"
              clearable
              placeholder="请选择竞价模式"
              @change="selectedChange"
            >
              <el-option label="一轮竞价" value="1"> </el-option>
              <el-option label="二轮竞价" value="2"> </el-option>
              <el-option label="三轮竞价" value="3"> </el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item
            label="显示选择"
            :span="2"
            style="text-align: center"
          >
            <div class="exhibition-div">
              <el-switch
                v-model="form.params.tenderRanking"
                active-color="#13ce66"
                inactive-text="竞价排名"
                style="margin-right: 30px"
              >
              </el-switch>

              <el-switch
                v-model="form.params.minimumPrice"
                active-color="#13ce66"
                inactive-text="最低价格"
                style="margin-left: 30px"
              >
              </el-switch>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="招标说明">
            <el-input v-model="form.params.tenderExplain" />
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="招标产品" class="margin-top" border>
          <el-descriptions-item label="产品选择">
            <el-select
              v-model="productSelectId"
              multiple
              placeholder="请选择招标产品"
              :disabled="isDisabled"
              style="width: 100%"
              @change="productSelect"
            >
              <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.productName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          class="margin-top"
          :column="2"
          border
          v-for="item in productss"
          :key="item.id"
        >
          <el-descriptions-item label="产品名称">
            <el-input v-model="item.productName" disabled />
          </el-descriptions-item>

          <el-descriptions-item label="采购数量">
            <!-- <el-input-number v-model="item.purchaseData" controls-position="right" :min="0" :max="999" @change="handleChange"/> -->
            <el-input-number
              v-model="item.purchaseData"
              controls-position="right"
              :min="0"
              :max="999"
            ></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="规格型号">
            <el-input v-model="item.productModel" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="采购单位">
            <el-input v-model="item.productUnit" disabled />
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="竞价时间" class="margin-top" :column="2" border>
          <el-descriptions-item
            v-for="(time, index) in times"
            :key="index"
            :span="2"
          >
            <template slot="label">
              {{ index + 1 + "轮竞价" }}
            </template>
            <el-date-picker
              type="datetimerange"
              v-model="time.timeArr"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="center"
            >
            </el-date-picker>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="定价时间" class="margin-top" :column="1" border>
          <el-descriptions-item label="定价时间">
            <el-date-picker
              v-model="calibration"
              type="datetimerange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="center"
            >
            </el-date-picker>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions
          title="邀约供应商"
          class="margin-top"
          :column="3"
          border
        >
          <el-descriptions-item label="发出邀约" :span:="3">
            <el-select
              v-model="form.params.supplierIds"
              style="width: 100%"
              value-key=""
              :disabled="isSupplierDisabled"
              placeholder="请选择供应商"
              clearable
              filterable
              multiple
              @change="SelectSupplier"
            >
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions
          class="margin-top"
          :column="2"
          border
          v-for="(item, index) in supplier"
          :key="index"
        >
          <el-descriptions-item label="供应商名">
            <el-input v-model="item.username" disabled />
          </el-descriptions-item>

          <el-descriptions-item label="公司名称">
            <el-input v-model="item.companyName" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            <el-input v-model="item.mobilePhone" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="积分数量">
            <el-input v-model="item.integral" disabled />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="ok">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
class TimeItem {
  constructor() {
    this.timeArr = [];
  }
}

import { mapGetters } from "vuex";
import {
  getTypeWithProjectAndProducts,
  getProductsByProjId,
  getAllSupplierByTenderProduct,
} from "@/api/purchaser-tender.js";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    tenderInfo: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {},
    },
    title: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: 0,
    },
    purchaser: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        params: {
          biddingMode: "3",
          calibrationEnd: "",
          calibrationStart: "",
          minimumPrice: true,
          purchaserId: "",
          roleId: "",
          tenderCharge: "",
          tenderCode: "",
          tenderExplain: "",
          tenderMode: "0",
          tenderName: "",
          tenderPhone: "",
          tenderProducts: [
            {
              productId: "",
              purchaseData: 100,
              purchaseUnit: "",
            },
          ],
          tenderProject: "",
          tenderRanking: true,
          tenderTel: "",
          tenderTime: "",
          tenderType: "",
          timeNodes: [
            {
              bindingEnd: "",
              bindingStart: "",
              round: 1,
            },
          ],
        },
        supplierIds: [],
        tenderId: "",
      },
      suppliers: [],
      projects: [],
      products: [],
      productss: [], //创建dom
      productSelectId: [],
      isDisabled: true, // 选择产品禁选
      isSupplierDisabled: true,
      times: [new TimeItem()],
      calibration: [],
      supplier: [],
      pickerOptions: {
        disabledDate: (time) => {
          const start = new Date().getTime() + 3600 * 1000 * 24 * 3;
          const end = start + 3600 * 1000 * 24 * 30;
          return time.getTime() < start || time.getTime() > end;
        },
      },
    };
  },
  computed: {
    ...mapGetters(["accountId", "roles"]),
    productTypes() {
      // 先获取到所有的类型
      let arr = this.projects.map((info) => {
        return info.typeBriefInfo;
      });
      let obj = {};
      return arr.reduce((item, next) => {
        obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
        return item;
      }, []);
    },
  },
  // created() {

  // },
  methods: {
    open() {
      console.log(this.purchaser);
      this.getProjects();
      // console.log(this.data)
      //this.form = this.tenderInfo;
      // 编辑弹窗 内部数据 填充
      this.form.params = this.tenderInfo;
      this.form.tenderId = this.tenderInfo.id;
      this.form.params.tenderType = this.tenderInfo.tenderType.id;
      this.form.params.tenderProject = this.tenderInfo.tenderProject.id;
      this.form.params.biddingMode = "" + this.tenderInfo.biddingMode;
      this.form.params.tenderMode = "" + this.tenderInfo.tenderMode;
      // 先清空times
      this.times = [];
      for (let index = 0; index < this.tenderInfo.biddingMode; index++) {
        const timeRound = this.tenderInfo.timeNodes.filter((t) => {
          return t.round === index + 1;
        });

        const item = new TimeItem();
        item.timeArr = [timeRound[0].bindingStart, timeRound[0].bindingEnd];
        this.times.push(item);
      }
      // 获取products
      this.getProducts(this.tenderInfo.tenderProject);
      this.productSelectId = this.tenderInfo.products.map((p) => {
        return p.id;
      });
      console.log("products：", this.products);
      // 清空productss
      this.productss = [];
      for (let i = 0; i < this.tenderInfo.products.length; i++) {
        // val : productId数组
        // 产品数组过滤出对应产品对象
        let newProductItem = this.tenderInfo.products.filter((item) => {
          return item.id == this.tenderInfo.products[i].id;
        });
        console.log("newProductItem:", newProductItem);
        this.productss.push(newProductItem[0]);
      }
      // calibration
      if (this.tenderInfo.calibrationStart !== undefined) {
        this.calibration = [
          this.tenderInfo.calibrationStart,
          this.tenderInfo.calibrationEnd,
        ];
      }

      //console.log("calibration:", this.calibration);
      this.getSupliers(this.productSelectId);
      this.form.params.supplierIds = this.tenderInfo.suppliers.map((s) => {
        return s.id;
      });
      // console.log(this.productType);
    },
    // 动态获取日期组件个数
    selectedChange(val) {
      if (!val) {
        this.form.params.biddingMode = "1";
        val = "1";
      }
      this.times.splice(0, this.times.length);
      for (let i = 0; i < parseInt(val); i++) {
        this.times.push(new TimeItem());
      }
    },

    productSelect(val) {
      this.suppliers.splice(0, this.suppliers.length);
      if (val.length !== 0) {
        this.getSupliers(val);
        // 清空数组
        this.productss.splice(0, this.productss.length);
        for (let i = 0; i < val.length; i++) {
          // val : productId数组
          // 产品数组过滤出对应产品对象
          let newProductItem = this.products.filter((item) => {
            return item.id == val[i];
          });
          newProductItem[0].purchaseData = 0;
          this.productss.push(newProductItem[0]);
        }
      } else {
        this.productss.splice(0, this.productss.length);
        this.suppliers = [];
        this.isSupplierDisabled = true;
      }
    },
    async getProjects() {
      // 如果当前登录的角色非采购员
      let purchaserId = "";
      if (
        this.$store.getters.roles.toString() !==
        "ebeda8021fccea8209458c3f89b80aad"
      ) {
        purchaserId = this.purchaser;
      } else {
        purchaserId = this.$store.getters.accountId;
      }
      const res = await getTypeWithProjectAndProducts({
        purchaserId: purchaserId,
      });
      if (res.code === 200) this.projects = res.data;
    },
    projectSelect(val) {
      if (val) {
        const res = this.projects.filter((info) => {
          return info.id === val;
        });
        this.form.params.tenderType = res[0].typeBriefInfo.id;
        // 调用函数
        this.getProducts(val);
      } else {
        this.form.params.tenderType = "找遍项目带出";
        this.productss = []; // 创建产品dom
        this.productSelectId = [];
        this.isDisabled = true;
      }
    },
    async getProducts(projectId) {
      const res = await getProductsByProjId({
        projectId: projectId,
        purchaserId: this.$store.getters.accountId,
      });
      if (res.code === 200) {
        this.products = res.data;
        this.isDisabled = false;
      }
    },

    async getSupliers(products) {
      const data = {
        pageParams: {
          page: 0,
          pageSize: 0,
        },
        productIds: products,
      };
      const res = await getAllSupplierByTenderProduct(data);
      if (res.code === 200) {
        this.suppliers = res.data.supplierByTenderProducts;
        this.isSupplierDisabled = false;
      }
    },

    SelectSupplier(val) {
      this.supplier.splice(0, this.supplier.length);
      for (let i = 0; i < val.length; i++) {
        let newSupplierItem = this.suppliers.filter((item) => {
          return item.id == val[i];
        });
        this.supplier.push(newSupplierItem[0]);
      }
    },

    initForm() {
      this.form = {
        params: {
          biddingMode: 3,
          calibrationEnd: "",
          calibrationStart: "",
          minimumPrice: true,
          purchaserId: "",
          roleId: "",
          tenderCharge: "",
          tenderCode: "",
          tenderExplain: "",
          tenderMode: 0,
          tenderName: "",
          tenderPhone: "",
          tenderProducts: [
            {
              productId: "",
              purchaseData: 100,
              purchaseUnit: "",
            },
          ],
          tenderProject: "",
          tenderRanking: true,
          tenderTel: "",
          tenderTime: "",
          tenderType: "",
          timeNodes: [
            {
              bindingEnd: "",
              bindingStart: "",
              round: 1,
            },
          ],
        },
        supplierIds: [],
        tenderId: "",
      };
    },
    cancel() {
      this.$emit("cancel");
      this.initForm();
    },
    ok() {
      this.form.params.purchaserId = this.accountId;
      this.form.params.roleId = this.roles.toString();
      this.form.params.calibrationStart = this.calibration[0];
      this.form.params.calibrationEnd = this.calibration[1];
      this.form.params.timeNodes = this.times.map((item, index) => {
        return {
          bindingStart: item.timeArr[0],
          bindingEnd: item.timeArr[1],
          round: index + 1,
        };
      });
      this.form.params.tenderProducts = this.productss.map((item) => {
        return {
          productId: item.id,
          purchaseData: item.purchaseData,
          purchaseUnit: item.productUnit,
        };
      });

      console.log(this.form);
      this.$emit("ok", this.form);
      this.initForm();
    },
  },
};
</script>

<style scoped>
.margin-top {
  margin-top: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 66px;
  height: 66px;
  line-height: 66px;
  text-align: center;
}
.avatar {
  width: 66px;
  height: 66px;
  display: block;
}
.exhibition-div {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
}
</style>
